package com.micangcaihang.micang.mvp.task.model;

import com.google.gson.reflect.TypeToken;
import com.micangcaihang.common.baserx.RxSchedulers;
import com.micangcaihang.common.http.ApiResult;
import com.micangcaihang.common.http.RxHelper;
import com.micangcaihang.common.utils.Convert;
import com.micangcaihang.common.utils.FileUtils;
import com.micangcaihang.micang.entity.FTaskBorrowerInfoEntity;
import com.micangcaihang.micang.entity.PickerEntity;
import com.micangcaihang.micang.entity.ProvinceEntity;
import com.micangcaihang.micang.http.ApiService;
import com.micangcaihang.micang.http.FApiService;
import com.micangcaihang.micang.http.request.FTaskBorrowerInfoRequest;
import com.micangcaihang.micang.mvp.task.contract.FTaskBorrowerInfoContract;

import java.lang.reflect.Type;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;

/**
 * <pre>
 *     author : Fandy
 *     e-mail : fandayongfly@gmail.com
 *     time   : 2017/07/17
 *     desc   : 风控 借款人信息
 *     version: 1.0
 * </pre>
 */

public class FTaskBorrowerInfoModel implements FTaskBorrowerInfoContract.Model {
    /**
     * 获取下拉框数据
     *
     * @param type
     * @return
     */
    @Override
    public Observable<ApiResult<List<PickerEntity>>> getPickerViewData(String type) {
        return ApiService.<ApiResult<List<PickerEntity>>>util_choose(type)
                .compose(RxSchedulers.observableIoToMain())
                .compose(RxHelper.handleResult());
    }

    /**
     * 获取借款人信息数据
     *
     * @param id
     * @return
     */
    @Override
    public Observable<ApiResult<FTaskBorrowerInfoEntity>> getBorrowerInfoData(String id) {
        return FApiService.<ApiResult<FTaskBorrowerInfoEntity>>risk_loaner(id)
                .compose(RxSchedulers.observableIoToMain())
                .compose(RxHelper.handleResult());
    }

    /**
     * 保存信息
     *
     * @param request
     * @return
     */
    @Override
    public Observable<ApiResult<Void>> savaLoanerData(FTaskBorrowerInfoRequest request) {
        return FApiService.<ApiResult<Void>>risk_save_loaner(request)
                .compose(RxSchedulers.observableIoToMain())
                .compose(RxHelper.handleResult());
    }

    /**
     * 保存信息
     *
     * @return
     */
    @Override
    public Observable<List<ProvinceEntity>> getProvinceDataData() {
        String json = FileUtils.getAssetFile("province.json");
        return Observable.create((ObservableOnSubscribe<List<ProvinceEntity>>) e -> {
            Type type = new TypeToken<List<ProvinceEntity>>() {
            }.getType();
            List<ProvinceEntity> provinceEntities = Convert.fromJson(json, type);
            e.onNext(provinceEntities);
            e.onComplete();
        }).compose(RxSchedulers.observableIoToMain());
    }
}
